package me.pinion.service;


import me.pinion.Log;
import me.pinion.model.book.Book;
import me.pinion.model.book.Chapter;

public class ChapterService extends Service{

    private static ChapterService chapterService;

    public static ChapterService getInstance(){
        if (chapterService == null){
            chapterService = new ChapterService();
        }
        return chapterService;
    }

    public Chapter create(String title, String text, Book book){
        Chapter chapter = book.getChapterByTitle(title);
        if (chapter == null){
            chapter = new Chapter();
            chapter.set("title", title)
                    .set("book_id", book.getInt("id"))
                    .setText(text);
            chapter.save();
        }else {
            chapter.setText(text);
            chapter.update();
        }
        Log.i(book.getBookname() + " => " + title);
        return chapter;
    }


    public Chapter update(Chapter chapter, String title, String text){
        chapter.set("title", title).setText(text);
        chapter.update();
        for (Chapter c: chapter.getBook().getChapters()){
            if (c.equals(chapter)){
                c.reset(chapter);
            }
        }
        return chapter;
    }
}
